<?php
/**
 * Created by IntelliJ IDEA.
 * User: baiyang
 * Date: 2018/6/29
 * Time: 下午3:41
 */

namespace Core\Common\Handler;


use Core\Common\Base\Config;
use Core\Common\Base\Log;

/**
 * 进程名与app.ini中的process.<进程名>相同, 都是小写
 * Class KafkaHandler
 * @package Core\Common\Handler
 */
class KafkaHandler
{
    const DISPATCH = false;

    private static $name = null;
    private static $timeout = null;
    private static $codec = null;

    public static function run()
    {
        if (is_null(self::$name)) {
            $tmp = explode('\\', __CLASS__);
            $processName = str_replace('Handler', '', array_pop($tmp));
            $parameter = Config::config('process.'.strtolower($processName).'.parameter');
            $arr = explode(',', $parameter);
            list($name, $timeout) = array_map('trim', $arr);
            self::$name = $name;
            self::$timeout = $timeout;
            self::$codec = Config::config('process.codec');
        }

        $kafka = \Core\Common\Base\Kafka::getInstance(self::$name);
        try {
            $message = $kafka->consume(self::$timeout);
            if (!$message) {
                return;
            }
            if (!class_exists('App\Consumer\CommonConsumer')) {
                Log::error(LOG_INFO, ['message' => "App\Consumer\CommonConsumer not found", ]);
                return 'no CommonConsumer';
            }
            $data = [
                'key' => $message->key,
                'value' => $message,
            ];
            call_user_func(['App\Consumer\CommonConsumer', 'run'], $data);
            return true;
        } catch (\Throwable $ex) {
            $detail = [
                'error_type' => 'KafkaHandler',
                'error_source' => self::$name,
                'query' => [],
            ];
            $context = [
                'error_code' => $ex->getCode(),
                'message' => $ex->getMessage(),
                'trace' => $ex->getTrace(),
            ];
            Log::error(LOG_ERR, $detail, $context);
            return 0;
        }
        return '';
    }
}